﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using LSEntity;
using LSInterFace;
using LSUtility;

namespace LSBLL
{
    public class MemoryBLL<TModel>
    {
        private readonly MemoryCache _memoryCache = null;
        private readonly MemoryEntity _memoryEntity = null;
        private readonly CacheItemPolicy _cacheItemPolicy = null;

        public MemoryBLL(MemoryEntity memoryEntity)
        {
            _memoryEntity = memoryEntity;
            _memoryCache = MemoryCache.Default;
            _cacheItemPolicy = new CacheItemPolicy();
            if (_memoryEntity.FilePaths.ListGetCount() > 0)
            {
                _cacheItemPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(_memoryEntity.FilePaths));
            }
            else
            {
                _cacheItemPolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.Add(_memoryEntity.TimeSpan));
            }
        }

        public virtual TModel MemoryModel()
        {
            if (_memoryCache.Contains(_memoryEntity.MemoryKey))
            {
                return (TModel)_memoryCache.Get(_memoryEntity.MemoryKey);
            }
            if (_memoryEntity.GetData != null)
            {
                var obj = _memoryEntity.GetData();
                MemorySet(obj);
                return (TModel)obj;
            }
            return default(TModel);
        }

        public virtual List<TModel> MemoryModelList()
        {
            if (_memoryCache.Contains(_memoryEntity.MemoryKey))
            {
                return (List<TModel>)_memoryCache.Get(_memoryEntity.MemoryKey);
            }
            var obj = _memoryEntity.GetData();
            MemorySet(obj);
            return (List<TModel>)obj;
        }

        public virtual void MemorySet(object sources)
        {
            if (_memoryCache.Contains(_memoryEntity.MemoryKey))
            {
                _memoryCache.Remove(_memoryEntity.MemoryKey);
            }
            _memoryCache.Set(_memoryEntity.MemoryKey, sources, _cacheItemPolicy);
        }

        public static TModel MemoryGet(string key)
        {
            var cache = MemoryCache.Default;
            if (MemoryCache.Default.Contains(key))
            {
                return (TModel)cache.Get(key);
            }
            return default(TModel);
        }

        public static List<TModel> MemoryListGet(string key)
        {
            var cache = MemoryCache.Default;
            if (cache.Contains(key))
            {
                return (List<TModel>)cache.Get(key);
            }
            return null;
        }
    }
}
